'use strict';
const db = uniCloud.database();
exports.main = async (event, context) => {
	
	if(event.product_type == 0){
		let res = await obtain_product(event)
		return res
	}else if(event.product_type == 1){
		let res = await obtain_product_detail(event)
		return res
	}else if(event.product_type == 2){
		let res = await class_product_list(event)
		return res
	}else if(event.product_type == 3){
		let res = await search_product(event)
		return res
	}
};

//获取指定页数的商品列表
const obtain_product = async (event) => {
	const product = db.collection('product_Detail');
	let res = await product.where({
		produce_info: {
			is_buy: true,
			is_show_index: true
		},
	}).orderBy('create_time','desc').skip(event.pageNum*event.pageSize).limit(event.pageSize).get();
	return res
}

//获取指定商品详情
const obtain_product_detail = async (event) => {
	const product = db.collection('product_Detail');
	let res = await product.where({_id:event._id}).get();
	return res
}

//获取指定分类下的商品列表
const class_product_list = async (event) => {
	const product = db.collection('product_Detail');
	if(event.price_sale == 0){
		let res = await product.where({
			produce_info:{
				product_faction: event._id
			}
		}).skip(event.pageNum*event.pageSize).limit(event.pageSize).get();
		return res
	}else if(event.price_sale == 1){
		let res = await product.where({
			produce_info:{
				product_faction: event._id
			}
		}).orderBy('produce_info.product_sale','desc').skip(event.pageNum*event.pageSize).limit(event.pageSize).get();
		return res
	}else {
		let res = await product.where({
			produce_info:{
				product_faction: event._id
			}
		}).orderBy('produce_info.product_min_price','asc').skip(event.pageNum*event.pageSize).limit(event.pageSize).get();
		return res
	}
}

//首页的模糊搜索
const search_product = async (event) => {
	const dbCmd = db.command;
	const product = db.collection('product_Detail');
	let res = product.where({
		produce_info:{
			name: new RegExp(event.text)
		}
	}).skip(event.pageNum * event.pageSize).limit(event.pageSize).get();
	return res
}